package com.google.gwt.livinglife.client.widgets;

import com.google.gwt.core.client.GWT;
import com.google.gwt.livinglife.client.LivingLife;
import com.google.gwt.livinglife.client.LivingLifeService;
import com.google.gwt.livinglife.client.LivingLifeServiceAsync;
import com.google.gwt.livinglife.client.LoginInfo;
import com.google.gwt.livinglife.client.NotLoggedInException;
import com.google.gwt.livinglife.client.data.ChallengeData;
import com.google.gwt.livinglife.client.data.UserIdData;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class ChallengeEntryForm extends BasicEntryForm {
	private Long group_id;
	private String group_name;
	@Override
	public void handleSubmit() {
		final ChallengeData challenge_data = new ChallengeData();
		FillBasicPost(challenge_data);
		LoginInfo login_info = LivingLife.getLogin_info();
		if (login_info == null || login_info.getUser_data() == null) {
			Window.alert("Please sign in");
			return;
		}
		challenge_data.setAuthor(new UserIdData(login_info.getUser_data()));
		challenge_data.setGroup_id(group_id);
		challenge_data.setGroup_name(group_name);
		LivingLifeServiceAsync service = GWT.create(LivingLifeService.class);
		try {
			service.addChallenge(challenge_data, new AsyncCallback<Long>() {

				@Override
				public void onFailure(Throwable caught) {
					handleError(caught);
				}

				@Override
				public void onSuccess(Long result) {
					challenge_data.setId(result);
					Window.Location.replace(LivingLife.getChallengeIdUrl(result));
				}
				
			});
		} catch (NotLoggedInException e) {
			handleError(e);
		}
		
	}
	private void handleError(Throwable caught) {
		Window.alert("Failed to post the challenge on server: please try at a later time. " + caught.getMessage());
	}
	public Long getGroup_id() {
		return group_id;
	}
	public void setGroup_id(Long groupId) {
		group_id = groupId;
	}
	public String getGroup_name() {
		return group_name;
	}
	public void setGroup_name(String groupName) {
		group_name = groupName;
	}
}
